"""
完整修复版启动脚本 - 处理 ForeignKey 导入问题
"""

import asyncio
import os
from pathlib import Path
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 确保导入所有必要的SQLAlchemy组件
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy import Column, String, Integer, Float, Text, Boolean, JSON, ForeignKey, DateTime, Enum, MetaData, text
from sqlalchemy.orm import relationship, declarative_base
from sqlalchemy.ext.declarative import declared_attr

# 创建自定义基类
Base = declarative_base()

# 初始化数据库连接
async def init_db(db_url):
    """初始化数据库连接"""
    logger.info(f"初始化数据库: {db_url}")
    
    # 创建数据目录
    data_dir = Path("data")
    if not data_dir.exists():
        data_dir.mkdir(parents=True, exist_ok=True)
    
    # 创建异步引擎 - SQLite专用配置
    if db_url.startswith('sqlite'):
        logger.info("检测到SQLite数据库，应用专用配置...")
        engine = create_async_engine(
            db_url,
            echo=False,
            connect_args={"check_same_thread": False}
        )
    else:
        logger.info("检测到非SQLite数据库，使用标准配置...")
        engine = create_async_engine(
            db_url,
            echo=False,
            pool_pre_ping=True,
            pool_recycle=3600,
            pool_size=10,
            max_overflow=20
        )
    
    # 创建会话工厂
    async_session_factory = async_sessionmaker(
        engine,
        class_=AsyncSession,
        expire_on_commit=False
    )
    
    # 测试数据库连接
    try:
        async with async_session_factory() as session:
            await session.execute(text("SELECT 1"))
            logger.info("✅ 数据库连接测试成功!")
    except Exception as e:
        logger.error(f"❌ 数据库连接测试失败: {str(e)}")
        return None, None
    
    return engine, async_session_factory

# 主函数
async def main():
    """主函数"""
    logger.info("🚀 离线语言播放系统 - 干净启动版")
    logger.info("=" * 50)
    
    # 数据库配置
    db_url = "sqlite+aiosqlite:///./data/app.db"
    
    # 初始化数据库
    engine, session_factory = await init_db(db_url)
    if not engine or not session_factory:
        logger.error("数据库初始化失败，无法继续")
        return
    
    # 预处理：将引擎和会话工厂注入到应用程序中
    import app.core.database
    app.core.database.engine = engine
    app.core.database.async_session_factory = session_factory
    
    # 确保Base类注入到应用程序中
    app.core.database.Base = Base
    
    # 创建FastAPI应用
    logger.info("创建应用程序...")
    from app.main import create_app
    app = create_app()
    
    # 启动服务器
    import uvicorn
    from app.core.config import settings
    
    # 使用不同的端口避免冲突
    port = 8001  # 改为 8001 避免端口冲突
    
    logger.info("系统信息:")
    logger.info(f"   API地址: http://{settings.HOST}:{port}")
    logger.info(f"   API文档: http://{settings.HOST}:{port}/docs")
    logger.info(f"   健康检查: http://{settings.HOST}:{port}/health")
    
    logger.info("启动API服务器...")
    config = uvicorn.Config(
        app=app,
        host=settings.HOST,
        port=port,
        reload=False,  # 禁用自动重载避免问题
        log_level="info" if not settings.DEBUG else "debug"
    )
    server = uvicorn.Server(config)
    await server.serve()

# 启动应用
if __name__ == "__main__":
    asyncio.run(main())